import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import subprocess
import threading
import os
from ttkthemes import ThemedStyle

class EnhancedPackageConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("Linux 软件包转换工具")
        self.root.geometry("800x650")
        self.style = ThemedStyle(root)
        self.style.set_theme("arc")
        
        # 初始化配置
        self.output_dir = os.getcwd()
        self.selected_files = []
        self.current_process = None
        self.use_container = False
        
        # 界面组件
        self.create_widgets()
        self.setup_menu()
        self.check_environment()

    def create_widgets(self):
        main_frame = ttk.Frame(self.root, padding=15)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 包类型选择
        type_frame = ttk.LabelFrame(main_frame, text="选择包类型", padding=10)
        type_frame.grid(row=0, column=0, pady=8, sticky="ew")
        
        self.pkg_type = tk.StringVar(value="deb")
        formats = ["DEB", "AppImage", "Snap", "Flatpak", "RPM", "PKG"]
        for i, fmt in enumerate(formats):
            ttk.Radiobutton(type_frame, text=fmt, variable=self.pkg_type,
                          value=fmt.lower()).grid(row=0, column=i, padx=5)

        # 容器模式开关
        mode_frame = ttk.Frame(main_frame)
        mode_frame.grid(row=1, column=0, pady=5, sticky="w")
        self.mode_btn = ttk.Checkbutton(mode_frame, text="容器模式", 
                                      command=self.toggle_container_mode)
        self.mode_btn.pack(side=tk.LEFT)

        # 文件选择
        file_frame = ttk.Frame(main_frame)
        file_frame.grid(row=2, column=0, pady=8, sticky="ew")
        
        self.file_entry = ttk.Entry(file_frame, width=60)
        self.file_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        ttk.Button(file_frame, text="选择文件", 
                 command=self.select_files).pack(side=tk.LEFT)

        # 输出路径
        output_frame = ttk.Frame(main_frame)
        output_frame.grid(row=3, column=0, pady=8, sticky="ew")
        self.output_entry = ttk.Entry(output_frame)
        self.output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        ttk.Button(output_frame, text="输出路径",
                 command=self.select_output).pack(side=tk.LEFT)

        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='determinate')
        self.progress.grid(row=4, column=0, pady=8, sticky="ew")
        self.status_label = ttk.Label(main_frame, text="就绪")
        self.status_label.grid(row=5, column=0)

        # 日志面板
        notebook = ttk.Notebook(main_frame)
        notebook.grid(row=6, column=0, sticky="nsew")
        
        log_frame = ttk.Frame(notebook)
        self.log_text = tk.Text(log_frame, wrap=tk.WORD, 
                              font=('微软雅黑', 9), height=15)
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.status_light = ttk.Label(log_frame, text="●", foreground="gray")
        self.status_light.place(x=10, y=5)
        notebook.add(log_frame, text="转换日志")

        # 操作按钮
        action_frame = ttk.Frame(main_frame)
        action_frame.grid(row=7, column=0, pady=8)
        ttk.Button(action_frame, text="开始转换", command=self.process_batch).pack(side=tk.LEFT)
        ttk.Button(action_frame, text="验证兼容性", command=self.check_compatibility).pack(side=tk.LEFT, padx=5)
        ttk.Button(action_frame, text="打开目录", command=self.open_directory).pack(side=tk.LEFT)
        ttk.Button(action_frame, text="生成备份", command=self.create_backup).pack(side=tk.LEFT, padx=5)

        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(6, weight=1)

    # 新增的核心方法
    def select_files(self):
        """选择待转换文件"""
        filetypes = (
            ('所有文件', '*.*'),
            ('DEB 包', '*.deb'),
            ('RPM 包', '*.rpm'),
            ('AppImage', '*.AppImage')
        )
        filenames = filedialog.askopenfilenames(title="选择要转换的软件包", filetypes=filetypes)
        if filenames:
            self.selected_files = list(filenames)
            self.file_entry.delete(0, tk.END)
            self.file_entry.insert(0, f"已选择 {len(filenames)} 个文件")
            self.log(f"已加载 {len(filenames)} 个待转换文件")

    def select_output(self):
        """设置输出目录"""
        directory = filedialog.askdirectory(title="选择输出目录", initialdir=self.output_dir)
        if directory:
            self.output_dir = directory
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, directory)
            self.log(f"输出目录已设置为：{directory}")

    def process_batch(self):
        """批量处理文件"""
        if not self.selected_files:
            messagebox.showwarning("警告", "请先选择要转换的文件")
            return
        
        def conversion_thread():
            try:
                total = len(self.selected_files)
                for i, file_path in enumerate(self.selected_files, 1):
                    self.log(f"正在转换文件 ({i}/{total}): {os.path.basename(file_path)}")
                    self.convert_file(file_path)
                    self.progress['value'] = (i/total)*100
                    self.root.update_idletasks()
                messagebox.showinfo("完成", "所有文件转换完成！")
            except Exception as e:
                messagebox.showerror("错误", f"转换过程中发生错误：{str(e)}")
            finally:
                self.current_process = None

        self.current_process = threading.Thread(target=conversion_thread)
        self.current_process.start()

    # 其他功能方法
    def toggle_container_mode(self):
        self.use_container = not self.use_container
        state = "启用" if self.use_container else "禁用"
        self.log(f"容器模式已{state}", "info")
        self.mode_btn.state(["selected"] if self.use_container else [])

    def check_compatibility(self):
        self.log("正在检测系统兼容性...")
        if self.use_container:
            self.check_container_env()
        else:
            self.check_native_env()

    def check_container_env(self):
        try:
            result = subprocess.run(["docker", "--version"], capture_output=True, text=True)
            if "Docker version" in result.stdout:
                self.status_light.config(foreground="green")
                self.log("Docker环境检测通过", "success")
            else:
                raise Exception("Docker未正确安装")
        except Exception as e:
            self.status_light.config(foreground="red")
            self.log(f"容器环境异常: {str(e)}", "error")

    def check_native_env(self):
        try:
            result = subprocess.run(["wsl", "--status"], capture_output=True, text=True)
            if "Default Version" in result.stdout:
                self.status_light.config(foreground="green")
                self.log("WSL环境检测通过", "success")
            else:
                raise Exception("WSL未正确配置")
        except Exception as e:
            self.status_light.config(foreground="red")
            self.log(f"原生环境异常: {str(e)}", "error")

    def convert_file(self, file_path):
        try:
            if self.use_container:
                self.container_convert(file_path)
            else:
                self.native_convert(file_path)
        except Exception as e:
            self.log(f"转换失败: {str(e)}", "error")

    def container_convert(self, file_path):
        volume_path = "/mnt/c" if "C:" in file_path else "/mnt/d"
        cmd = [
            "docker", "run", "--rm",
            "-v", f"{os.path.dirname(file_path)}:{volume_path}/input",
            "-v", f"{self.output_dir}:{volume_path}/output",
            "deepin/llkiller",
            "ll-killer-go", "convert",
            "--type", self.pkg_type.get(),
            "--input", f"{volume_path}/input/{os.path.basename(file_path)}",
            "--output", f"{volume_path}/output"
        ]
        self.run_command(cmd)

    def native_convert(self, file_path):
        wsl_path = file_path.replace("\\", "/").replace("C:/", "/mnt/c/")
        cmd = [
            "wsl", "ll-killer-go", "convert",
            "--type", self.pkg_type.get(),
            "--input", wsl_path,
            "--output", f"{wsl_path}.llpkg"
        ]
        self.run_command(cmd)

    def run_command(self, cmd):
        process = subprocess.Popen(cmd,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT,
                                 text=True,
                                 encoding='utf-8')
        while True:
            output = process.stdout.readline()
            if not output and process.poll() is not None:
                break
            self.log(output.strip())

        if process.returncode != 0:
            raise RuntimeError("命令执行失败")

    def create_backup(self):
        if not self.selected_files:
            messagebox.showwarning("警告", "请先选择要备份的文件")
            return
            
        backup_dir = os.path.join(self.output_dir, "backup")
        os.makedirs(backup_dir, exist_ok=True)
        
        for file in self.selected_files:
            try:
                os.link(file, os.path.join(backup_dir, os.path.basename(file)))
                self.log(f"已创建备份: {os.path.basename(file)}", "success")
            except Exception as e:
                self.log(f"备份失败: {str(e)}", "error")

    def open_directory(self):
        os.startfile(self.output_dir)

    def setup_menu(self):
        menubar = tk.Menu(self.root)
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="退出", command=self.root.quit)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="关于", command=self.show_about)
        menubar.add_cascade(label="帮助", menu=help_menu)
        
        self.root.config(menu=menubar)

    def show_about(self):
        messagebox.showinfo("关于", "Linux 软件包转换工具\n版本 2.0\n支持容器化转换和批量处理")

    def check_environment(self):
        try:
            subprocess.run(["wsl", "--status"], check=True, stdout=subprocess.PIPE)
            subprocess.run(["wsl", "which", "ll-killer-go"], check=True)
            self.log("环境检测通过，准备就绪", "success")
        except Exception as e:
            messagebox.showerror("环境错误", f"系统环境检测失败：{str(e)}")
            self.root.destroy()

    def log(self, message, msg_type="info"):
        color_map = {
            "info": "black",
            "success": "green",
            "error": "red",
            "warning": "orange"
        }
        self.log_text.configure(state="normal")
        self.log_text.insert(tk.END, message + "\n", msg_type)
        self.log_text.tag_config(msg_type, foreground=color_map.get(msg_type, "black"))
        self.log_text.see(tk.END)
        self.log_text.configure(state="disabled")

if __name__ == "__main__":
    root = tk.Tk()
    app = EnhancedPackageConverter(root)
    root.mainloop()